package demo;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/7/17-07-17-14:37
 * @Description：使用反射编写泛型数组
 */
public class ArrayCopyTest {
    public static void main(String[] args) {
        int[] a = { 1, 2, 3 };
        int[] newArray = new int[a.length*2];
        System.arraycopy(a,0,newArray,0,a.length);
        System.out.println(Arrays.toString(newArray));
        a = (int[]) goodCopyOf(a,10);
        System.out.println(Arrays.toString(a));     //[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]

        String[] b = { "Tom", "Dick", "Harry"};
        b = (String[]) goodCopyOf(b, 10);
        System.out.println(Arrays.toString(b));       //[Tom, Dick, Harry, null, null, null, null, null, null, null]

        System.out.println("The following call will generate an exception.");
        b = (String[]) badCopyOf(b,10);
    }

    /**
     * 创建一个包含所有旧元素的新数组
     * @param a
     * @param newLength
     * @return  返回一个新长度的数组，但数组类型和旧数组不一致
     */
    private static Object[] badCopyOf(Object[] a, int newLength) {     //错误  抛出异常  ClassCastException
        Object[] newArray = new Object[newLength];
        System.arraycopy(a,0,newArray,0,Math.min(a.length,newLength));
        return newArray;
    }

    /**
     * 创建一个和a一种类型的新数组并含有所有的旧元素
     * @param a 旧数组
     * @param newLength 需要创建的新数组的长度
     * @return newArray  创建的新数组
     */
    public static Object goodCopyOf(Object a, int newLength) {
        Class c1 = a.getClass();
        if(!c1.isArray()){
            return null;
        }
        Class componentType = c1.getComponentType();
        int length = Array.getLength(a);
        Object newArray = Array.newInstance(componentType,newLength);     //返回一个给定类型、给定维数的新数组
        System.arraycopy(a,0,newArray,0,Math.min(length,newLength));
        return newArray;
    }
}
